package com.cyf.plc.ui.fragment

import android.content.Intent
import android.graphics.Typeface
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.cyf.library.util.logi
import com.cyf.plc.R
import com.cyf.plc.adapter.RoomLightAdapter
import com.cyf.plc.base.BaseFragment
import com.cyf.plc.bean.*
import com.cyf.plc.constant.Constants
import com.cyf.plc.databinding.FragmentLightMainBinding
import com.cyf.plc.model.PlcRoom
import com.cyf.plc.plc.PlcExecutor
import com.cyf.plc.ui.SettingActivity
import com.cyf.plc.util.State
import com.cyf.plc.util.setValueText
import com.cyf.plc.util.showToast
import com.cyf.plc.viewmodel.MainViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author：Lei on 2020/12/12
 */
@ExperimentalCoroutinesApi
class MainLightFragment :
    BaseFragment<MainViewModel, FragmentLightMainBinding>(){
    override fun layoutId(): Int {
        return R.layout.fragment_light_main
    }

    var selectPanelIndex = 0
    var plcRoomList = ArrayList<PlcRoom>()
    override fun initView() {
        mViewBinding.recyclerView.layoutManager = LinearLayoutManager(activity,LinearLayoutManager.HORIZONTAL,false)
        mViewBinding.recyclerView.adapter = RoomLightAdapter(plcRoomList,activity, RoomLightAdapter.OnItemClickListener {
            var plcRoom = plcRoomList.get(it)
            selectPanelIndex = it
            mViewBinding.tvRoomName.text = plcRoom.roomName
            updatePanel(panelMap[selectPanelIndex])
        })
        initClick()
        //初始化故障点位
        getSystemFaultAttributes()
        var sourceHanSansCN = Typeface.createFromAsset(activity?.getAssets(), "fonts/BebasNenu.ttf")
        mViewBinding.tvShowTemp.typeface = sourceHanSansCN
        mViewBinding.tvPanelHumidity.typeface = sourceHanSansCN
        mViewBinding.tvPanelSetTemp.typeface = sourceHanSansCN
        mViewBinding.tvPanelTemp.typeface = sourceHanSansCN
    }

    fun initClick(){
        //设置
        mViewBinding.ivSetting.setOnClickListener {
            startActivity(Intent(this.context, SettingActivity::class.java))
        }
        //制冷
        mViewBinding.ivCold.setOnClickListener{
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_MODE_ID, Constants.MODE_COLD, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //制热
        mViewBinding.ivHot.setOnClickListener{
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_MODE_ID, Constants.MODE_HOT, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //通风
        mViewBinding.ivWind.setOnClickListener{
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_MODE_ID, Constants.MODE_WIND, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //除湿
        mViewBinding.ivArefaction.setOnClickListener{
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_MODE_ID, Constants.MODE_CHUSHI, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //系统开关
        mViewBinding.ivPower.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_POWER_ID, if (powerOn) Constants.POWER_OFF else Constants.POWER_ON, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //离家
        mViewBinding.ivOutHome.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_OUT_HOME_ID, if (outHome) Constants.POWER_OFF else Constants.POWER_ON, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //节能
        mViewBinding.ivEnergyConservation.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_ENERGY_CONSERVATION_ID, if (energyConservation) Constants.POWER_OFF else Constants.POWER_ON, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //风量
        mViewBinding.ivWindSpeed.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.SYSTEM_WIND_ID, if (windLow) Constants.WIND_HIGH else Constants.WIND_LOW, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        //面板开关、设定温度
        mViewBinding.ivPanelSwitch.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.PANEL_SWITCH_ID+Constants.PANEL_TEMP_LENGTH*selectPanelIndex, if (panelSwitchOn) Constants.POWER_OFF else Constants.POWER_ON, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        mViewBinding.ivTempMinus.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.PANEL_SET_TEMP_ID+Constants.PANEL_TEMP_LENGTH*selectPanelIndex, (--setTemp)*10f, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
        mViewBinding.ivTempPlus.setOnClickListener {
            var plcWriteAttribute = PlcWriteAttribute(Constants.PANEL_SET_TEMP_ID+Constants.PANEL_TEMP_LENGTH*selectPanelIndex, (++setTemp)*10f, Constants.VW)
            PlcExecutor.write(plcWriteAttribute)
        }
    }

    override fun onStart() {
        super.onStart()
        "onStart".logi("MainLightFragment")
        PlcExecutor.updatePlcSystem()
    }

    var powerOn = false
    var outHome = false
    var energyConservation = false
    var windLow = false
    var panelMap = HashMap<Int,PanelStatus>()
    var panelSwitchOn = false
    var setTemp = 20
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateSystem(systemStatus: SystemStatus){
        systemStatus.toString().logi("MainLightFragment")
        setValueText(systemStatus.temp,mViewBinding.tvShowTemp,"℃")
        mViewBinding.systemStatus = systemStatus
        powerOn = systemStatus.power
        outHome = systemStatus.leaveHome
        energyConservation = systemStatus.noFault
        windLow = (systemStatus.volumeValue == Constants.WIND_LOW)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updatePanelList(panelHashMap: HashMap<Int, PanelStatus>){
        panelMap = panelHashMap
        var panelStatus = panelHashMap[selectPanelIndex]
        updatePanel(panelStatus)
    }

    var deviceBean: DeviceBean = DeviceBean("000000000000")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun updateFloorRoomInfo(deviceBean: DeviceBean){
        if (this.deviceBean.deviceId.equals(deviceBean.deviceId)){
            return
        }
        this.deviceBean = deviceBean
        deviceBean.deviceId?.let {
            mViewModel.requestYunConfig(it)
                .observe(viewLifecycleOwner, Observer { state ->
                    //获取到配置啦
                    when (state) {
                        is State.Success -> {
                            val log = "获取配置成功:" + state.data
                            log.logi()
                            val response : FloorRoomResponse = state.data
                            var dataBeanList = response.data
                            if (!dataBeanList.isNullOrEmpty()) {
                                plcRoomList.clear()
                                for (dataBean in dataBeanList) {
                                    val pos = dataBeanList.indexOf(dataBean)
                                    val floorId = pos + 1
                                    for (pannel in dataBean.pannelList!!){
                                        val roomId = pannel.order?.toInt()
                                        val plcRoom = PlcRoom(
                                            roomId?.minus(1),
                                            pannel.name,
                                            floorId.toLong()
                                        )
                                        plcRoomList.add(plcRoom)
                                    }
                                }
                                PlcExecutor.roomSize = plcRoomList.size
                                (mViewBinding.recyclerView.adapter as RoomLightAdapter).notifyDataSetChanged()
                                mViewBinding.tvRoomName.text = plcRoomList[0].roomName
                            }
                        }
                    }
                })
        }
    }

    fun updatePanel(panelStatus: PanelStatus?){
        if (panelStatus != null){
            panelStatus.toString().logi("MainLightFragment")
            setValueText(panelStatus.temp.toString(),mViewBinding.tvPanelTemp,"℃")
            setValueText(panelStatus.humidity.toString(),mViewBinding.tvPanelHumidity,"%")
            setValueText(panelStatus.setTemp.toString(),mViewBinding.tvPanelSetTemp,"℃")
            panelSwitchOn = panelStatus.power
            setTemp = panelStatus.setTemp
            mViewBinding.ivPanelSwitch.setImageResource(if (panelStatus.power)R.drawable.img_panel_on else R.drawable.img_panel_off)
        }
    }

    private fun getSystemFaultAttributes() {
        mViewModel.getAllPlcFaultAddress().observe(viewLifecycleOwner, Observer {
            PlcExecutor.plcFaultList = it
        })
    }

    override fun createViewModel(): MainViewModel = activity?.run {
        ViewModelProvider(this)[MainViewModel::class.java]
    } ?: throw Exception("Invalid Activity")
}